//
//  PlSOnSiteLoader.m
//  Injector
//
//  Created by ∞ on 30/11/07.
//  Copyright 2007 Emanuele Vulcano. All rights reserved.
//

#import "PlSOnSiteLoader.h"
#import "PlSSIMBLManager.h"
#import "PlSPlugIn.h"
#import "PlSAppSpecifier.h"
#import "PlSInputManagerManager.h"
#import "PlSCFPreferences.h"

#import <Carbon/Carbon.h>

@implementation PlSOnSiteLoader

+ (id) sharedInstance {
	static id myself = nil; if (!myself)
		myself = [self new];
	
	NSLog(@"myself = %@", myself);
	return myself;
}

+ (void) installLaterOnMainThread {
	NSAutoreleasePool* pool = [NSAutoreleasePool new];
	[[self sharedInstance] performSelectorOnMainThread:@selector(scheduleInstallOnMainThread) withObject:nil waitUntilDone:NO];
	[pool release];
}

- (void) scheduleInstallOnMainThread {
	NSAutoreleasePool* pool = [NSAutoreleasePool new];
	[self performSelector:@selector(install) withObject:nil afterDelay:0.01];
	[pool release];	
}

- (void) install {
	NSAutoreleasePool* pool = [NSAutoreleasePool new];
	@try {	
		PlSSIMBLManager* mgrSIMBL = [[[PlSSIMBLManager alloc] init] autorelease];
		PlSInputManagerManager* mgrIM = [[[PlSInputManagerManager alloc] init] autorelease];
		
		PlSCFPreferences* prefs = [[[PlSCFPreferences alloc] init] autorelease];
		mgrSIMBL.preferencesController = prefs;
		mgrIM.preferencesController = prefs;
		
		[mgrSIMBL rescan];
		[mgrIM rescan];
		
		NSMutableArray* arr = [NSMutableArray array];
		[arr addObjectsFromArray:mgrSIMBL.plugIns];
		[arr addObjectsFromArray:mgrIM.plugIns];
		
		for (PlSPlugIn* pin in arr) {
			if (!pin.isManaged || !pin.isLoadable) continue;
			
			if (pin.canCheckQuarantineOnUserVisiblePath &&
				[pin.userVisiblePath hasPrefix:NSHomeDirectory()]) {
				NSURL* url = [NSURL fileURLWithPath:pin.userVisiblePath];
				FSRef ref;
				CFURLGetFSRef((CFURLRef) url, &ref);
				
				NSDictionary* attrs = nil;
				if (LSCopyItemAttribute(&ref, kLSRolesAll, kLSItemQuarantineProperties, (CFTypeRef*) &attrs) == noErr) {
					[attrs release];
					L0Log(@"plug-in %@ is quarantined inside home folder -- discarded.", pin.identifier);
					continue; // we don't load quarantined plug-ins in the home folder.
				}
			}
			
			L0Log(@"%@", pin.identifier);
			if ([PlSAppSpecifier anySpecifier:pin.appSpecifiers isCompatibleWithApplication:[NSBundle mainBundle]]) {
				L0Log(@"(%@ seems to be compatible, loading.)", pin.identifier);
				
				BOOL loaded = [pin loadNow];
				L0Log(@"Attempted to load %@, result = %d (1 means success).", pin.identifier, loaded);
			} else
				L0Log(@"%@ does not request compatibility with with this app. Not loading.", pin.identifier);
		}
	} @catch (NSException* ex) {
		NSLog(@"PlugSuit got an exception while trying to install plug-ins in this application. This is likely a bug in PlugSuit; please contact <plugsuit@infinite-labs.net> about this.\nThe exception was: %@", ex);
	}
	
	[pool release];
}

@end
